package com.baijia.ticket;

import org.springframework.util.Assert;

/**
 * @title AbstractTicket
 * @desc 实现Ticket，并且处理ticket的状态和策略 
 * @author caoliang
 * @date 2015年12月5日
 * @version 1.0
 */
public abstract class AbstractTicket implements Ticket, TicketState {

    private static final long serialVersionUID = 1805823217306987284L;

    private String id;

    /** 联系的TGT */
    private TicketGrantingTicketImpl ticketGrantingTicket;
    
    /** 下面两个属性，用于做策略，如多久不使用就删掉，而不是等到超时时间 */
    private long lastTimeUsed;

    private long previousLastTimeUsed;

    private long creationTime;

    private int countOfUses;
    
    protected AbstractTicket() {
        // nothing to do
    }

    public AbstractTicket(final String id, final TicketGrantingTicketImpl ticket) {
        Assert.notNull(id, "id cannot be null");

        this.id = id;
        this.creationTime = System.currentTimeMillis();
        this.lastTimeUsed = System.currentTimeMillis();
        this.ticketGrantingTicket = ticket;
    }

    @Override
    public final String getId() {
        return this.id;
    }

    protected final void updateState() {
        this.previousLastTimeUsed = this.lastTimeUsed;
        this.lastTimeUsed = System.currentTimeMillis();
        this.countOfUses++;
    }

    @Override
    public final int getCountOfUses() {
        return this.countOfUses;
    }

    @Override
    public final long getCreationTime() {
        return this.creationTime;
    }

    @Override
    public final TicketGrantingTicket getGrantingTicket() {
        return this.ticketGrantingTicket;
    }

    @Override
    public final long getLastTimeUsed() {
        return this.lastTimeUsed;
    }

    @Override
    public final long getPreviousTimeUsed() {
        return this.previousLastTimeUsed;
    }

    @Override
    public final int hashCode() {
        return 34 ^ this.getId().hashCode();
    }

    @Override
    public final String toString() {
        return this.id;
    }
}
